// pages/print/near/near.js
var utils = require("../../../utils/utils.js");
var locationImg = '/img/192.png';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    lat:'',
    lon:'',
    list:[],
    key:'',
    isOut:'',
    showMap:false,
    shopInfo:{},
    firstOpen:0,
    page:1,
    limit:2000
  },
  goLocationPrint(e){
    var lat = e.currentTarget.dataset.lat;
    var name = e.currentTarget.dataset.name;
    var address = e.currentTarget.dataset.address;
    var lon = e.currentTarget.dataset.lon;
    wx.openLocation({
      name:name,
      address:address,
      latitude:parseFloat(lat),
      longitude:parseFloat(lon),
      scale: 18
    })
  },
  chooseMarket(e){
    var index = e.detail.markerId;
    if(index==0){
        return false;
    }
    this.setData({
      shopInfo:this.data.list[index-1]
    })
  },
  changemap(){
    this.setData({
      showMap:!this.data.showMap,
      shopPrintListShow:false
    })
    if(this.data.showMap){
        this.setData({
            page:1,
            limit:2000
        })
    }else{
        this.setData({
            page:1,
            limit:20
        })
    }
    this.getIndex();
    // this.addMarker();
  },
  keywordInput(e){
    this.setData({
        key:e.detail.value
    })
    if(this.data.showMap){
        this.setData({
            page:1,
            limit:2000
        })
    }else{
        this.setData({
            page:1,
            limit:20
        })
    }
    this.getIndex()
},
goDetail(e){
  var info = e.currentTarget.dataset.info;
   wx.navigateTo({
     url: '/pages/print/shopDetail/shopDetail?id='+info.id+'&shopName='+info.shopName+'&from='+this.data.from,
   })
},
// 地图标记
addMarker(){
    var list = this.data.list;
    var markerArray = [];
    var userObj = {
        id:0,
        latitude:this.data.lat,
        longitude:this.data.lon,
        width:62,
        height:70,
        iconPath:'../../../img/196.png',
        callout:{
            content:'当前位置',
            display:'BYCLICK',
            borderWidth:1,
            borderRadius:5,
            borderColor:'#2062ed',
            padding:10
        }

    }
    markerArray.push(userObj);
    for(var i=0;i<list.length;i++){
        var obj = {};
        obj.id = i+1;
        obj.latitude = parseFloat(list[i].lat)
        obj.iconPath = locationImg
        obj.longitude = parseFloat(list[i].lng)
        obj.width = 50
        obj.height = 50
        obj.callout = {
            content:list[i].shopName,
            display:'BYCLICK',
            borderWidth:1,
            borderRadius:5,
            borderColor:'#2062ed',
            padding:10
        }
        markerArray.push(obj)
    }
    this.mapCtx.addMarkers({
        markers:markerArray,
        clear: true,
        complete(res) {
          
        }
      })
      let points = []
      
      markerArray.forEach(item => {
    	let obj = {
          latitude: item.latitude,
          longitude: item.longitude
        }
        points.push(obj)
    })
    var newArray = [];
    newArray.push({latitude:this.data.lat,longitude:this.data.lon})
    for(var i=0;i<markerArray.length;i++){
            let obj = {
                latitude: markerArray[i].latitude,
                longitude: markerArray[i].longitude
              }
            newArray.push(obj);
    }
      this.mapCtx.includePoints({
        padding:[100,100,100,100],
        points:newArray
     })
     this.setData({
        shopInfo:this.data.list[0]
      })
},
checkboxChange(e){
    this.setData({
        isOut:e.detail.value=='y'?'1':''
    })
    if(this.data.showMap){
        this.setData({
            page:1,
            limit:2000
        })
    }else{
        this.setData({
            page:1,
            limit:20
        })
    }
    this.getIndex()
},
hideFix(){
    this.setData({
        shopPrintListShow:false
    })
},
goPrint(e){
    var sn = e.currentTarget.dataset.sn;
    wx.setStorageSync('machineQrCode',sn)
    wx.navigateBack();
},
  choosePrint(e){
      var index = e.currentTarget.dataset.shopindex;
      var list = this.data.list;
      if(list[index].device.length>1){
            this.setData({
                shopPrintList:list[index].device,
                shopPrintListShow:true
            })
      }else{
        wx.setStorageSync('machineQrCode',list[index].device[0].machineQrCode)
        wx.navigateBack();
      }
  },
  //获取附近打印机
  getIndex(){
    var that = this;
    // that.data.lat that.data.lon
    utils.request('home/nearbyList',{lat:that.data.lat,lng:that.data.lon,distribution:that.data.isOut,page:that.data.page,limit:that.data.limit,keywords:that.data.key}, function (res) {
      wx.stopPullDownRefresh()
      wx.hideNavigationBarLoading()
      if(res.data.code==200){
        wx.hideLoading()
        if(that.data.showMap){
            that.setData({
                list:res.data.data.rows,
                kmlate:res.data.data.nearbyKm,
                shopInfo:{}
              })
        }else{
            if (that.data.page == 1) {
                that.setData({
                    page: res.data.data.page,
                    pageCount: res.data.data.pageCount,
                    kmlate:res.data.data.nearbyKm,
                    list:res.data.data.rows,
                })
            } else {
                var array = that.data.list;
                var newA =array.concat(res.data.data.rows)
                that.setData({
                    page: res.data.data.page,
                    kmlate:res.data.data.nearbyKm,
                    pageCount:res.data.data.pageCount,
                    list:newA
                })
            }
        }
       
        // that.addMarker();
      }else{
        utils.toast(res.data.msg)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:function (options) {
      wx.setNavigationBarTitle({
        title:options.name||'附近门店',
      })
      this.setData({
          from:options.from||''
      })
      // this.getIndex()
    this.getLocationAuth()
    // this.mapCtx = wx.createMapContext('mapId')
  },
    //获取当前位置
    getLocationAuth(){
      var that = this;
      wx.authorize({
      scope: 'scope.userLocation',
      success(res) {
        wx.getLocation({
          type: 'wgs84',
          success(res) {
            that.setData({
              lat:res.latitude,
              lon:res.longitude
            })
            that.getIndex(res.latitude,res.longitude)
          }
        })
      },
      fail() {
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.userLocation']){
              wx.showModal({
                title: '提示',
                content: '检测到未获得定位权限，请进行授权后重新尝试',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success(res) {
                        if (res.authSetting['scope.userLocation']) {
                          wx.getLocation({
                            type: 'wgs84',
                            success(res) {
                              that.setData({
                                lat:res.latitude,
                                lon:res.longitude
                              })
                              that.getIndex()
                            }
                          })
                        }else{
                          
                        }
                      },
                      fail(res) {
                       
                      }
                    })
                  }else{
                    
                  }
                }
              })
            } else {
              
            }
          },
          fail(err){
            
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (that.data.firstOpen == 1) {
      that.getLocationAuth()
    } else {
      that.setData({
        firstOpen: 1
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if(this.data.showMap==true){
        this.setData({
            page: 1,
            limit:2000
        })
        this.getIndex();
        wx.stopPullDownRefresh()
    }else{
        this.setData({
            page: 1,
            limit:20
        })
        this.getIndex();
        wx.stopPullDownRefresh()
    }   
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.page == this.data.pageCount) {
        return false;
    } else {
        var page = parseInt(this.data.page) + 1
        this.setData({
            page: page
        })
        this.getIndex();
    }
  }
})